<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" :style="{ marginLeft: '20px',marginTop:'20px' } " @click="showDialog=true">添加角色</el-button>
      </div>
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column align="center" width="200" label="序号">
          <template #default="obj">
            {{ obj.$index + 1+(pageParams.page-1)*pageParams.pagesize }}
          </template>
        </el-table-column>
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template #default="{row}">
            <div v-if="!row.isEdit">{{ row.name }}</div>
            <!-- 3. 使用复制的数据 双向绑定 -->
            <el-input v-else v-model="row.editRowData.name" />
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <template #default="{row}">
            <div v-if="!row.isEdit">{{ row.state ? '已启用' : '未启用' }}</div>
            <!-- 3. 使用复制的数据 双向绑定 -->
            <el-switch v-else v-model="row.editRowData.state" :inactive-value="0" :active-value="1" />
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template #default="{row}">
            <div v-if="!row.isEdit">{{ row.description }}</div>
            <!-- 3. 使用复制的数据 双向绑定 -->
            <el-input v-else v-model="row.editRowData.description" type="textarea" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{row}">
            <div v-if="!row.isEdit">
              <el-button size="mini" type="text" @click="onPreShow(row.id)">分配权限</el-button>
              <!-- 2. 点击事件修改isEdit的值 -->
              <el-button size="mini" type="text" @click="row.isEdit =true">编辑</el-button>
              <el-button size="mini" type="text">

                <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="confirmDel(row.id)">
                  <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>

                </el-popconfirm>
              </el-button>

            </div>
            <div v-else>
              <!-- 2. 点击事件修改isEdit的值 -->
              <el-button size="mini" type="primary" @click="btnEditOK(row)">确定</el-button>

              <el-button size="mini" @click="onCancel(row)">取消</el-button>

            </div>

          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="center">
        <!-- 放置分页组件 -->
        <el-pagination :page-size="pageParams.pagesize" layout="prev, pager, next" :total="pageParams.total" @current-change="changePage" />
      </el-row>
      <el-dialog width="500px" title="新增角色" :visible.sync="showDialog">
        <!-- 表单内容 -->
        <el-form ref="addForm" :model="formData" label-width="120px" :rules="rules">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="formData.name" style="width:300px" size="mini" />
          </el-form-item>

          <el-form-item label="启用">
            <el-switch v-model="formData.state" size="mini" :inactive-value="0" :active-value="1" />
          </el-form-item>

          <el-form-item label="角色描述" prop="description">
            <el-input v-model="formData.description" type="textarea" :rows="3" style="width:300px" size="mini" />
          </el-form-item>

          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="12">
                <el-button type="primary" size="mini" @click="onsubmit">确定</el-button>

                <el-button size="mini" @click="showDialog=false">取消</el-button>

              </el-col>

            </el-row>

          </el-form-item>

        </el-form>

      </el-dialog>

    </div>
    <el-dialog :visible.sync="permShow" title="分配权限" @close="permShow = false">
      <!-- expand-on-click-node关闭点击折叠节点  -->
      <!-- show-checkbox开启复选 -->
      <!-- default-checked-keys设置默认选中的节点 -->
      <!-- node-key告诉树，id字段是唯一的 -->
      <!-- check-strictly：关闭父子联动 -->
      <el-tree
        ref="treeRef"
        show-checkbox
        :check-strictly="true"
        :data="permList"
        :props="{label:'name'}"
        default-expand-all
        :expand-on-click-node="false"
        node-key="id"
        :default-checked-keys="checkedPermIds"
      />
      <el-row justify="center" type="flex" style="padding: 20px;">
        <el-button size="mini" type="primary" @click="onAssignPerm">分配权限</el-button>
        <el-button size="mini" @click="permShow = false">取消</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getPermissionListAPI } from '@/api/permission'
import { addRoleAPI, assignPermAPI, delRoleAPI, getRoleDetailAPI, getRoleListAPI, updateRoleAPI } from '@/api/role'
import { arrayToTree } from '@/utils'

export default {
  name: 'Role',
  data() {
    return {
      // 准备数组，用来保存角色已有的权限id
      checkedPermIds: [],
      permShow: false, // 分配权限弹出层
      permList: [],
      showDialog: false,
      list: [],
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0
      },
      formData: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      }

    }
  },
  watch: {
    showDialog(val) {
      if (!val) {
        this.$refs.addForm.resetFields()
        this.formData = {
          name: '',
          description: '',
          state: 0
        }
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const res = await getRoleListAPI(this.pageParams)
      this.list = res.rows
      this.pageParams.total = res.total
      this.list.forEach((item) => {
        // item.isEdit = false
        // 1. 给list中每个元素, 分配一个isEdit 表示是否正在编辑的 开关表示
        this.$set(item, 'isEdit', false)
        // 复制一份备份数据
        this.$set(item, 'editRowData', {
          name: item.name,
          description: item.description,
          state: item.state
        })
      })
    },
    changePage(newPage) {
      this.pageParams.page = newPage
      this.getRoleList()
    },
    async onsubmit() {
      await this.$refs.addForm.validate()
      await addRoleAPI(this.formData)
      this.showDialog = false
      this.$message.success('添加角色成功')
      this.getRoleList()
    },
    onCancel(row) {
      row.isEdit = false
      row.editRowData = {
        name: row.name,
        description: row.description,
        state: row.state
      }
    },
    async btnEditOK(row) {
      if (!row.editRowData.name) return this.$message.error('请输入角色名称')
      if (!row.editRowData.description) return this.$message.error('请输入描述')
      await updateRoleAPI({
        id: row.id,
        ...row.editRowData
      })
      this.$message.success('修改角色成功')
      this.getRoleList()
    },
    async confirmDel(id) {
      await delRoleAPI(id)
      this.$message.success('删除角色成功')
      this.getRoleList()
    },
    async onPreShow(id) {
      const res = await getPermissionListAPI()
      const { permIds } = await getRoleDetailAPI(id)
      this.checkedPermIds = permIds
      this.roleId = id
      this.permList = arrayToTree(res)
      this.permShow = true
    },
    async onAssignPerm() {
      const checkedKeys = this.$refs.treeRef.getCheckedKeys()
      await assignPermAPI({ id: this.roleId, permIds: checkedKeys })
      this.$message.success('分配权限成功')
      this.permShow = false
    }
  }
}
</script>
<style scoped>
  .role-operate {
  padding: 10px;
}
</style>
